import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {DrawerForm, ProDescriptions, ProForm, ProFormSelect, ProFormText, ProTable} from '@ant-design/pro-components';
import {Button, Drawer, Image, message} from 'antd';
import React, {useRef, useState} from 'react';
import {deleteById, saveUser, search, updateById} from "@/services/ant-design-pro/api";
import {RecordKey} from "@ant-design/pro-utils/es/useEditableArray";

export default () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const [userDetail, setUserDetail] = useState({} as API.CurrentUser);


  const columns: ProColumns<API.CurrentUser>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '用户名称',
      dataIndex: 'username',
    },
    {
      title: '用户账户',
      dataIndex: 'userAccount',
      copyable: true,
      hideInTable: true,
    },
    {
      title: '用户头像',
      dataIndex: 'avatarUrl',
      render: (_, record) => (
        <div>
          <Image src={record?.avatarUrl} width={80}/>
        </div>
      )
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueEnum: {
        0:
          {
            text: '女',
          },
        1: {
          text: '男',
        },
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '用户状态',
      dataIndex: 'userStatus',
      valueEnum: {
        0: {
          text: '可用',
          status: 'Default',
        },
        1: {
          text: '禁用',
          status: 'Success',
        },
      },
    },
    {
      title: '用户角色',
      dataIndex: 'userRole',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '用户',
          status: 'Default',
        },
        1: {
          text: '管理员',
          status: 'Success',
        },
      },
    },
    {
      title: '星球编号',
      dataIndex: 'planetCode',
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => (
        <>
          <Button
            size={"small"}
            key="editable"
            onClick={() => {
              action?.startEditable?.(record.id);
            }}
          >
            编辑
          </Button>
          <Button
            size={"small"}
            key="detail"
            onClick={() => {
              setUserDetail(record)
              setShowDetail(true)
            }}
          >
            详情
          </Button>
        </>

      ),
    },
  ];
  return (
    <>
      <ProTable<API.CurrentUser>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async () => {
          const res = await search();
          return {
            data: res.data
          }
          // return request<{
          //   data: API.CurrentUser[];
          // }>('/user/search', {
          //   params,
          // });
        }}


        editable={{
          onSave: async (key: RecordKey | undefined, row: API.CurrentUser) => {
            const res = await updateById(row);
            if (res.data === true) {
              message.success("修改成功")
              actionRef.current?.reload();
            } else {
              message.error("修改失败")
            }
            return Promise.resolve()
          },

          onDelete: async (key: RecordKey, row: API.CurrentUser) => {
            const res = await deleteById(row?.id);
            if (res.data === true) {
              message.success("删除成功")
              actionRef.current?.reload();
            } else {
              message.error("删除失败")
            }
            return Promise.resolve()
          }
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            // listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            key={"addForm"}
            type="primary"
            onClick={() => {
              setDrawerVisit(true);
            }}
          >
            <PlusOutlined/>
            新增用户
          </Button>
        ]}
      />

      <Drawer
        visible={showDetail}
        onClose={() => {
          setShowDetail(false)
        }}
      >
        {showDetail && <ProDescriptions<API.CurrentUser>
          request={async () => ({
            data: userDetail,
          })}
          columns={columns}
          column={1}

        />}

      </Drawer>

      <DrawerForm
        onOpenChange={setDrawerVisit}
        title="新增用户"
        open={drawerVisit}
        onFinish={async (user: API.CurrentUser) => {
          const res = await saveUser(user);
          if (res.data === true) {
            message.success('提交成功');
            actionRef.current?.reload();
          } else {
            message.error('提交失败');
          }
          return true;
        }}
        drawerProps={{
          destroyOnClose: true,
        }}
      >


        <ProForm.Group>
          <ProFormText width="md" name="username" label="用户姓名" placeholder="请输入姓名"/>
          <ProFormText width="md" name="useAccount" label="登录账号" placeholder="请输入登录账号"/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText width="md" name="avatarUrl" label="头像" placeholder="这里不完善，只能输入网络链接"/>
          <ProFormSelect
            options={[
              {
                value: 1,
                label: '男',
              },
              {
                value: 0,
                label: '女'
              }
            ]}
            width="xs"
            name="gender"
            label="性别"
          />
        </ProForm.Group>

        <ProForm.Group>
          <ProFormText width="md" name="userPassword" label="密码" placeholder="请输入密码"/>
          <ProFormText width="md" name="phone" label="手机号" placeholder="请输入登录手机号"/>
        </ProForm.Group>

        <ProForm.Group>
          <ProFormText width="md" name="email" label="邮箱" placeholder="请输入邮箱"/>
          <ProFormSelect
            options={[
              {
                value: 0,
                label: '可用',
              },
              {
                value: 1,
                label: '禁用',
              },
            ]}
            width="xs"
            name="userStatus"
            label="用户状态"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            options={[
              {
                value: 0,
                label: '普通用户',
              },
              {
                value: 1,
                label: '管理员',
              },
            ]}
            width="xs"
            name="userRole"
            label="用户角色"
          />
          <ProFormText width="md" name="planetCode" label="星球编号" placeholder="请输入星球编号"/>
        </ProForm.Group>
      </DrawerForm>

    </>


  );
};
